package de.tempel.pong.collison;

import java.awt.geom.Point2D;
import java.util.List;

import processing.core.PApplet;
import de.tempel.pong.objects.Ball;
import de.tempel.pong.objects.Racket;
import de.tempel.pong.objects.basic.Vector;

/**
 * 
 * Manager für SubsequentDiscreteCollisionDetection.
 * 
 * @author mathias
 * 
 */
public class SubsequentDiscreteCollisionManager extends
		AbstractCollisionManager {

	/**
	 * 
	 * @param ball
	 * @param rackets
	 * @param window
	 */
	public SubsequentDiscreteCollisionManager(Ball ball, List<Racket> rackets,
			PApplet window) {
		super(ball, rackets, window);
	}

	@Override
	public void checkCollisions(float tpf) {

		boolean ballHasCollision = checkCollisions(ball);
		if (ballHasCollision) {
			return;
		}

		Ball pseudoBall = new Ball(ball);

		// 10 SubSchritte
		float subSequentStep = tpf / 10;

		// Berechne die nächsten 10 Sub Positionen
		for (int i = 0; i < 10; i++) {

			// Bewege den PseudoBall
			pseudoBall.move(subSequentStep);

			// Zeichne den PseudoBall
			window.fill(150);
			pseudoBall.draw(window);
			window.fill(255);

			// Prüfe ob Psyeudoball eine Kollision hat
			boolean pseudoBallHasCollision = checkCollisions(pseudoBall);
			if (pseudoBallHasCollision) {

				// Setze Ball an die Position des Pseudoballs und ändere
				// Bewegungsrichtung
				Point2D pseudoballPosition = pseudoBall.getPosition();
				Vector pseudoballMovement = pseudoBall.getMovement();

				ball.setPosition(pseudoballPosition);
				ball.setMovement(pseudoballMovement);

			}

		}
	}

	private boolean checkCollisions(Ball b) {

		Vector oldBallDirection = b.getMovement();
		Vector newBallDirection = new Vector(oldBallDirection.getX(),
				oldBallDirection.getY() * -1);

		/**
		 * Obere Kante
		 */
		Point2D ballBasePoint = b.getPosition();
		if (ballBasePoint.getY() < 0) {
			b.setMovement(newBallDirection);
			return true;
		}

		/**
		 * Untere Kante
		 */
		if (ballBasePoint.getY() + b.getWidth() > window.getHeight()) {
			b.setMovement(newBallDirection);
			return true;
		}

		/**
		 * Kollisionen mit Schläger
		 */
		if (rackets != null) {

			for (Racket r : rackets) {

				if (r.getRectangle().intersects(b.getRectangle())) {

					// System.out.println("Has collision!");
					Vector newXBallDirection = new Vector(
							oldBallDirection.getX() * -1,
							oldBallDirection.getY());
					b.setMovement(newXBallDirection);

					return true;
				}

			}

		}

		return false;
	}
}
